package com.cosina.game.colorball;

import java.util.ArrayList;
import java.util.List;



public class BallGame {
	private final Ball[][] balls ;
	
	private final int xCount, yCount;
	private final List<Ball> ambulance = new ArrayList<Ball>();
	
	private int score = 0;

	public static final int MEDICINE_COUNT = 3;
	
	public BallGame(int xCount, int yCount,Difficulty difficulty){
		this.xCount = xCount;
		this.yCount = yCount;
		
		balls = new Ball[yCount][xCount];
		for (int y = 0; y < yCount; y++) {
			for (int x = 0; x < xCount; x++) {
				int color = BallView.getRandomColor(difficulty.getCode());
				balls[y][x] = new Ball(x,y,color,this);
			}
		}
	}
	
	public int getScore(){
		return score;
	}
	
	public void cureAmbulance(){
		for(Ball each : ambulance){
			each.cure();
		}
	}

	public boolean diagnosis(int x, int y){
		ambulance.clear();
		
		getBall(x, y).sick(ambulance);
		
		if(ambulance.size() < BallGame.MEDICINE_COUNT ){
			cureAmbulance();
			
			return false;
		}
		
		score += IntegralRule.calSocre(ambulance.size());
		rebuilt();
		return true;
	}
	
	public Ball getBall(int x, int y){
		try{
			return balls[y][x];
		}catch(IndexOutOfBoundsException ex) {
			return Ball.DEAD_BALL;
		}
	}
	
	
	private void rebuilt(){
		int nullColumnCount = 0;
		for(int x=0; x<xCount; x++){
			int deadBallCount = 0;
			for(int y=yCount-1; y>=0; y--){
				if(balls[y][x].health == false){
					deadBallCount = deadBallCount + 1 ;
				}else if(deadBallCount > 0){
					balls[y+deadBallCount][x] = balls[y][x];
					balls[y+deadBallCount][x].update(x,y+deadBallCount);
					balls[y][x] = Ball.DEAD_BALL;
					
				}
			}
			
			
			if(nullColumnCount > 0){
				for(int y=yCount-1; y>=0; y--){
					balls[y][x - nullColumnCount] = balls[y][x];
					balls[y][x - nullColumnCount].update(x - nullColumnCount, y);
					balls[y][x] = Ball.DEAD_BALL;
				}
			}
			if(deadBallCount == yCount)
				nullColumnCount++;
		}
	}

	public boolean checkNoInfectPossiable() {
		for(int y=yCount-1; y>=0; y--){
			for(int x=0; x<xCount; x++){
				Ball ball = balls[y][x];
				if(ball.health == false)
					continue;
				ambulance.clear();
				ball.sick(ambulance);
				int size = ambulance.size();
				cureAmbulance();
				if(size >= 3){
					return false;
				}
			}
		}
		return true;
	}
}
